#!/usr/bin/env python
# -*- coding: utf-8 -*-

from teamupshoppers import app
from flask          import Flask, views, jsonify, render_template, request, session, flash, url_for, redirect
from werkzeug       import check_password_hash, generate_password_hash
from db             import DB

import logging
from flask.ext.login import (LoginManager, current_user, login_required,
                            login_user, logout_user, UserMixin, AnonymousUser,
                            confirm_login, fresh_login_required)
login_manager = LoginManager()

login_manager.session_protection = "strong"

class User(UserMixin):
    def __init__(self, name, id, active=True):
        self.name = name
        self.id = id
        self.active = active

    def is_active(self):
        return self.active
    
@login_manager.user_loader
def load_user(id):
    user = DB().query('''select * from user where id = ?''',
                    [id],
                    one=True)
    return User(user["name"],user["id"])

login_manager.setup_app(app)

class Login(views.MethodView):
    """
    if somebody whant to ask as about user
    """
    def get(self):
        return render_template('index.html')
    """
    """
    def post(self):
        required = ["username", "password"]
        for r in required:
            if r not in request.form:
                flash("Error: {0} is required.".format(r))
                return render_template("index.html")
        error = ""       
        username = request.form["username"]
        passwd = request.form["password"]
        user = DB().query("select * from user where name = ?",
                        [request.form["username"]],
                        one=True)
        if user is None:
            error = "Invalid username"
        elif not check_password_hash(user["pw_hash"],
                                     request.form["password"]):
            error = "Invalid password"
        else:
            error = "You were logged in"
            remember = request.form.get("remember", "no") == "yes"
            login_user( User(user["name"],user["id"]), remember=remember)
        flash( error )
        return redirect(url_for("main"))

"""Logs the user out."""
class Logout(views.MethodView):
    @login_required
    def get(self):
        return self._logout()
        
    @login_required
    def post(self):
        return self._logout()
        
    def _logout(self):
        flash("You were logged out")
        logout_user()
        return redirect(url_for("main"))
